import { getOs, uniShowModal } from "./rewriteUni";
import permision from "./lib/wa-permission/permission.js";
import dayjs from "dayjs";

/**
 * 打开外部url连接
 */
export function openUrl(url: string) {
  // 跳转外部链接h5
  // #ifdef H5
  window.location.href = url;
  // #endif
  // #ifdef APP-PLUS
  plus.runtime.openURL(url);
  // #endif
}

/**
 * 打开gps定位
 */
export let openGPS = () => {
  const os = getOs();
  if (os === "android") {
    openGPS = openAndroidGps;
  } else if (os === "ios") {
    openGPS = openIosGps;
  }
  openGPS();
  function openAndroidGps() {
    const context: any = plus.android.importClass("android.content.Context");
    const locationManager: any = plus.android.importClass(
      "android.location.LocationManager"
    );
    const main: any = plus.android.runtimeMainActivity();
    const mainSvr = main.getSystemService(context.LOCATION_SERVICE);
    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
      const Intent: any = plus.android.importClass("android.content.Intent");
      const Settings: any = plus.android.importClass(
        "android.provider.Settings"
      );
      const intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      main.startActivity(intent); // 打开系统设置GPS服务页面
    } else {
      console.log("手机系统的定位已经打开");
    }
  }
  function openIosGps() {
    const ios: any = plus.ios;
    const cllocationManger = ios.import("CLLocationManager");
    const enable = cllocationManger.locationServicesEnabled();
    const status = cllocationManger.authorizationStatus();
    plus.ios.deleteObject(cllocationManger);
    if (enable && status != 2) {
      console.log("手机系统的定位已经打开");
    } else {
      const UIApplication = ios.import("UIApplication");
      const application2 = UIApplication.sharedApplication();
      const NSURL2 = ios.import("NSURL");
      // const setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
      // const setting2 = NSURL2.URLWithString("App-Prefs:root=LOCATION_SERVICES");
      const setting2 = NSURL2.URLWithString("app-settings:");
      //const setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
      // const setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION_SERVICES");
      application2.openURL(setting2);
      plus.ios.deleteObject(setting2);
      plus.ios.deleteObject(NSURL2);
      plus.ios.deleteObject(application2);
    }
  }
};

export interface PhotoAlbumItem {
  id?: string;
  /**文件路径 */
  path: string;
  /**文件名称 */
  fileName: string;
  /**创建时间 YYYY-MM-DD HH:mm:ss */
  creationDate: string;
  width?: number;
  height?: number;
  size?: number;
}

/**
 * * 获取相册图片信息列表
 * @param num 获取数量
 * @returns
 */
export let getPhotoAlbum = (num?: number): Promise<PhotoAlbumItem[]> => {
  //#ifdef APP-PLUS
  const os = getOs();
  if (os === "android") getPhotoAlbum = runAndroid;
  else if (os === "ios") getPhotoAlbum = runIos;
  return getPhotoAlbum(num);
  function runIos() {
    return new Promise<PhotoAlbumItem[]>((resolve, reject) => {
      const galleryModule = uni.requireNativePlugin("dcp-Gallery");
      galleryModule.getGalleryImages(
        {
          count: num,
        },
        (ret: {
          status: number;
          data: PhotoAlbumItem[];
          msg: string;
          total: number;
        }) => {
          if (ret && ret.status === 200) {
            resolve(ret.data);
          } else reject();
        }
      );
    });
  }
  function runAndroid() {
    return new Promise<PhotoAlbumItem[]>(async (resolve, reject) => {
      const AUTH = "android.permission.READ_EXTERNAL_STORAGE";
      const code = await permision.requestAndroidPermission(AUTH);
      if (code != 1) {
        return uniShowModal("请前往权限管理，打开本app的相册读取权！").finally(
          () => {
            permision.gotoAppPermissionSetting();
            reject();
          }
        );
      }

      let imageList = [];
      let MediaStore: any = plus.android.importClass(
        "android.provider.MediaStore"
      );
      let photoColumns = [
        MediaStore.Images.Media._ID,
        MediaStore.Images.Media.DATA,
        MediaStore.Images.Media.DATE_ADDED,
      ];
      let main: any = plus.android.runtimeMainActivity();
      let resolver = main.getContentResolver();
      plus.android.importClass(resolver);
      let cursor = resolver.query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        photoColumns,
        null,
        null,
        null
      );
      plus.android.importClass(cursor);
      while (cursor.moveToNext()) {
        const id: string = cursor.getString(
          cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        );
        const path: string = cursor.getString(
          cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        );
        const creationDate: number = cursor.getLong(
          cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
        );
        const data: PhotoAlbumItem = {
          id: id,
          path,
          creationDate: dayjs(creationDate).format("YYYY-MM-DD HH:mm:ss"),
          fileName: path.slice(path.lastIndexOf("/")),
        };
        imageList.push(data);
        if (num && imageList.length >= num) break;
      }
      cursor.close();
      return resolve(imageList);
    });
  }
  //#endif
  uniShowModal("暂不兼容非APP");
};
